<template>
    <page-container title="管理员列表">
         <template #extra>
             <el-button 
                 style="margin-right: 20px;"
                 type="primary" 
                 @click="addAdmins"
             >添加管理员</el-button>
     </template>
         <el-table 
             :data="admins" 
             style="width: 100%" 
             v-loading="tableLoading"
             @selection-change="handleSelectionChange"
         > 
             <el-table-column type="selection"  width="55" />
             <el-table-column type="index" label="序号" width="100"/>
             <el-table-column prop="username" label="用户名">
                 <template #default="scope">
                     <el-popover effect="light" width="auto" trigger="contextmenu">
                         <template #reference>
                             <el-tag>{{ scope.row.username }}</el-tag>
                         </template>
                     </el-popover>
                 </template>
             </el-table-column>
             <el-table-column prop="fullName" label="管理员姓名" />
             <el-table-column prop="email" label="邮箱"/>
             <el-table-column prop="phone" label="手机号" />
             <el-table-column prop="role" label="角色" />
             <el-table-column prop="isEnabled" label="状态">
                 <template #default="{ row }">
                     <el-switch
                         v-model="row.isEnabled"
                         :active-value="1"
                         :inactive-value="0"
                         @change="(val) => handleStatusChange(row, val)"
                         :loading="row.statusLoading"
                     />
                 </template>
             </el-table-column>
             <el-table-column prop="lastLoginTime" label="最后登录时间">
                <template #default="{ row }">
                     {{ formatDateTime(row.lastLoginTime) }}
                 </template>
            </el-table-column>
             <el-table-column prop="createTime" label="创建时间" >
                 <template #default="{ row }">
                     {{ formatDateTime(row.createTime) }}
                 </template>
             </el-table-column>
             <el-table-column label="操作" width="180">
                 <template #default="scope">
                    <el-button 
                         type="primary" 
                         @click="updateAdmins(scope.row)"
                     >
                     编辑
                     </el-button>
                     <el-button 
                         type="danger" 
                         @click="deleteAdmins(scope.row)"
                     >
                     删除
                     </el-button>
                 </template>
             </el-table-column>
 
             <template #empty>
                 <el-empty description="暂无数据" />
             </template>
       
            
         </el-table>
         <el-drawer 
             v-model="dialogVisible" 
             title="管理员信息" 
             width="50%" 
             direction="rtl"
         >
             <el-form 
                 :model="form" 
                 label-width="120px" 
                 ref="formRef"
             >
                 <el-form-item label="用户名" required>
                     <el-input 
                         v-model="form.username"
                         placeholder="请输入用户名"
                     />
                 </el-form-item>
                 <el-form-item label="密码" required>
                     <el-input 
                         type="password"
                         v-model="form.password"
                         placeholder="请输入密码"
                     />
                 </el-form-item>
                 <el-form-item label="角色" required>
                    <el-select 
                        v-model="form.role" 
                        placeholder="请选择角色"
                        clearable
                    >
                        <el-option label="sub_admin" value="sub_admin" />
                        <el-option label="admin" value="admin" />
                    </el-select>
                 </el-form-item>
                 <el-form-item>
                     <el-button type="primary" @click="saveAdmin">保存</el-button>
                     <el-button @click="dialogVisible = false">取消</el-button>
                 </el-form-item>
             </el-form>
         </el-drawer>
     </page-container>
 </template>
 
 <script setup>
 import PageContainer from '@/components/PageContainer.vue'
 import{onMounted, ref} from 'vue'
 import {getAdminInfo, updateAdminStatus, addAdmin, deleteAdmin} from '@/api/admin'
 import {ElMessage, ElMessageBox} from 'element-plus'
const admins = ref([])
const tableLoading = ref(true)
const dialogVisible = ref(false)
const form = ref({})
const addAdmins = () => {
    dialogVisible.value = true
    form.value = {}
}
const updateAdmins =(row) => {
    dialogVisible.value = true
    form.value = {...row}
}
const loadAdmins = async () => {
    tableLoading.value = true
    try {
        const res = await getAdminInfo()
        console.log(res)
        admins.value = res.data
    } catch (error) {
        ElMessage.error('获取管理员列表失败', error)
    } finally {
        tableLoading.value = false
    }
}
const saveAdmin = async () => {

    try {
        const res = form.value.adminId ? await updateAdminStatus(form.value) : await addAdmin(form.value)
        console.log(res)
        if (res.code === 200) {
            ElMessage.success(form.value.adminId?'更新管理员成功':'添加管理员成功')
            await loadAdmins()
            dialogVisible.value = false
        } else {
            ElMessage.error(res.message || form.value.adminId?'更新管理员失败':'添加管理员失败')
        }
    } catch (error) {
        ElMessage.error(form.value.adminId?'更新管理员失败':'添加管理员失败', error)
    }
}
const deleteAdmins = async (row) => {
    try {
        await ElMessageBox.confirm('确定要删除该管理员吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(async () => {
            const res = await deleteAdmin(row.adminId)
            console.log(res)
            if (res.code === 200) {
                ElMessage.success('删除管理员成功')
                await loadAdmins()
            } else {
                ElMessage.error(res.message || '删除管理员失败')
            }
        })
    } catch (error) {
        ElMessage.error('删除管理员失败', error)
    }
}
const formatDateTime = (dateStr) => {
    if (!dateStr) return '--'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    })
}

// 处理状态切换
const handleStatusChange = async (row, value) => {
    try {
        row.statusLoading = true  // 显示加载状态
        const res = await updateAdminStatus({ 
            adminId: row.adminId,
            isEnabled: value  // 只发送状态值
        })
        
        console.log('状态更新响应：', res)
        
        if (res.code === 200) {
            ElMessage.success('状态更新成功')
            await loadAdmins()  // 重新加载列表
        } else {
            row.enabled = !value  // 如果失败，恢复原状态
            ElMessage.error(res.message || '状态更新失败')
        }
    } catch (error) {
        console.error('状态更新失败：', error)
        row.enabled = !value  // 如果出错，恢复原状态
        ElMessage.error('状态更新失败：' + error.message)
    } finally {
        row.statusLoading = false  // 隐藏加载状态
    }
}

onMounted(()=>{
    setTimeout(() => {
        loadAdmins()
    }, 1000)
})
 </script>
 
 <style scoped> 
 
 
 </style>
 